package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;//工具类

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY +id;
        //先查redis
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {  //存在,直接返回
            //isnotblank只有在里边是字符串时才是true
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //到这里是null OR 空字符串
        //判断命中的是否是空值
        if (shopJson != null) {//不是null，那就只能是空字符串了
            return null;
        }
    //实现缓存重建
        //获取互斥锁
        String lockKey = "lock:shop:"+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //判断是否获取成功
            if (!isLock) {//失败-休眠重试
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //成功根据id查数据库，写入redis
            shop = getById(id);
            Thread.sleep(500);//模拟查询时间
            if (shop == null) {//数据库不存在，返回错误
                //将空值写入redis（防止缓存穿透）
                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //数据库里存在，写入redis缓存
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unlock(lockKey);//释放互斥锁
        }
        return shop;
    }




    @Override
    public Result queryById(Long id) {

        //解决缓存穿透
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,CACHE_SHOP_TTL,TimeUnit.SECONDS,Shop.class,this::getById);

        //解决缓存击穿-互斥锁
        Shop shop = queryWithMutex(id);

        //解决缓存击穿-逻辑过期
        //Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY,id,CACHE_SHOP_TTL,TimeUnit.SECONDS, Shop.class,this::getById);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空！");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //先判断是否需要按照坐标查询
        if (x==null || y==null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page);
        }
        //计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = (current + 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis，按照距离排序、分页
        String key = SHOP_GEO_KEY+typeId;
        int pageSize = SystemConstants.DEFAULT_PAGE_SIZE;
        int count = current * pageSize; // 由于GEORADIUS不支持skip，这里查询到第N页的总条数
        // 使用GEORADIUS命令替代GEOSEARCH（Redis 3.2+支持）
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .radius(
                        key,
                        new Circle(new Point(x, y), new Distance(5000)), // 中心点和半径（5000米）
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                                .includeDistance() // 包含距离
                                .sortAscending() // 按距离升序
                                .limit(count) // 查询到第N页的总条数（用于后续截取）
                );
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        //截取从from到end的集合
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        // 跳过前面的记录，只取当前页的数据
        list.stream()
                .skip(from)
                .limit(pageSize)
                .forEach(result -> {
                    String shopId = result.getContent().getName();
                    ids.add(Long.valueOf(shopId));
                    distanceMap.put(shopId, result.getDistance());
                });
        //查数据库
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }

    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);//模拟休眠200ms
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //不添加ttl
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }
}
